package com.heima.comment.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        从请求头中获取userID
        String userId = request.getHeader("userId");
//        判断userID不为空且不等于0
        if (!StringUtils.isEmpty(userId) && !userId.equals("0")){
//            将用户信息放到本地线程池中
            User user = new User();
            user.setUserId(Integer.parseInt(userId));
            AppThreadLocalUtil.set(user);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//          释放本地线程
        AppThreadLocalUtil.remove();
    }
}
